package com.treasure.mall.zbqmallapi.controller;

import com.treasure.mall.biz.dto.community.CommentsSearchCondition;
import com.treasure.mall.biz.dto.community.CommunityArticleSaveDTO;
import com.treasure.mall.biz.dto.community.CommunityArticleSearchCondition;
import com.treasure.mall.biz.entity.community.CommunityArticleLikePO;
import com.treasure.mall.biz.entity.community.CommunityArticlePO;
import com.treasure.mall.biz.entity.community.CommunityCommentLikePO;
import com.treasure.mall.biz.entity.community.CommunityCommentPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.community.CommunityArticleService;
import com.treasure.mall.biz.service.core.community.CommunityCommentService;
import com.treasure.mall.biz.service.core.user.UserFollowService;
import com.treasure.mall.biz.vo.PageDataVO;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.ienum.community.CommunityEnums;
import com.treasure.mall.zbqmallapi.annotation.AccessControl;
import com.treasure.mall.zbqmallapi.mapstruct.CommunityMapStruct;
import com.treasure.mall.zbqmallapi.vo.community.CommentsVO;
import com.treasure.mall.zbqmallapi.vo.community.CommunityArticleDetailVO;
import com.treasure.mall.zbqmallapi.vo.community.CommunityArticleVO;
import com.treasure.mall.zbqmallapi.vo.community.MyCommunityArticleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * <p> 社区相关接口
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallapi.controller
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/7/28 9:57 上午
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 *
 */
@RestController
@RequestMapping("/community")
public class CommunityController {

    @Autowired
    private CommunityArticleService communityArticleService;
    @Autowired
    private CommunityCommentService communityCommentService;
    @Autowired
    private UserFollowService followService;

    /**
     * 获取社区文章列表
     *
     * @param condition
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/article/list")
    public ApiResult articleList(
            CommunityArticleSearchCondition condition,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "20") int size) {
        condition.setStatus(CommunityEnums.AuditStatus.SUCCESS.getCode());

        Page<CommunityArticlePO> pages = communityArticleService.findAll(page, size, condition);
        PageDataVO<CommunityArticleVO> pageDataVO = new PageDataVO<>();
        pageDataVO.setPageCount(pages.getTotalPages());
        pageDataVO.setPageIndex(page);
        pageDataVO.setPageSize(size);
        pageDataVO.setTotal(pages.getTotalElements());
        pageDataVO.setRows(CommunityMapStruct.Instance.communityArticlePos2vos(pages.getContent()));
        return ApiResult.ok(pageDataVO);
    }

    /**
     * 获取我的作品
     *
     * @param condition
     * @param user
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/article/list/my")
    @AccessControl(needLogin = true)
    public ApiResult myArticleList(
            CommunityArticleSearchCondition condition,
            @CurrentUser UserPO user,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "20") int size) {
        condition.setUserId(user.getUserId());
        Page<CommunityArticlePO> pages = communityArticleService.findAll(page, size, condition);
        PageDataVO<MyCommunityArticleVO> pageDataVO = new PageDataVO<>();
        pageDataVO.setPageCount(pages.getTotalPages());
        pageDataVO.setPageIndex(page);
        pageDataVO.setPageSize(size);
        pageDataVO.setTotal(pages.getTotalElements());
        pageDataVO.setRows(CommunityMapStruct.Instance.myCommunityArticlePos2vos(pages.getContent()));
        return ApiResult.ok(pageDataVO);
    }

    /**
     * 我喜欢的作品
     *
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/article/list/mylike")
    public ApiResult myLikeList(
            Long userId,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "20") int size) {
        Page<CommunityArticleLikePO> likePOS = communityArticleService.likes(userId, page, size);

        PageDataVO<CommunityArticleVO> pageDataVO = new PageDataVO<>();
        pageDataVO.setPageCount(likePOS.getTotalPages());
        pageDataVO.setPageIndex(page);
        pageDataVO.setPageSize(size);
        pageDataVO.setTotal(likePOS.getTotalElements());

        List<CommunityArticleVO> vos = new ArrayList<>();
        likePOS.getContent().forEach(p -> vos.add(new CommunityArticleVO(p.getArticlePO())));

        pageDataVO.setRows(vos);
        return ApiResult.ok(pageDataVO);
    }


    /**
     * 发布社区图文
     *
     * @param user
     * @param dto
     * @return
     */
    @PostMapping("/article/save")
    @AccessControl(needLogin = true)
    public ApiResult saveArticle(@CurrentUser UserPO user, @RequestBody CommunityArticleSaveDTO dto) {
        dto.setUser(user);
        communityArticleService.save(dto);
        return ApiResult.ok(true);
    }

    /**
     * 文章详情
     *
     * @param articleId
     * @return
     */
    @GetMapping("/article/detail")
    public ApiResult articleDetail(@CurrentUser UserPO user, Long articleId) {
        CommunityArticlePO po = communityArticleService.findById(articleId);
        if (po != null) {
            CommunityArticleDetailVO vo = CommunityMapStruct.Instance.communityArticleDetailPo2vo(po);
            vo.setImages(po.getImages());
            if (user != null) {
                vo.setLiked(communityArticleService.isUserLiked(articleId, user.getUserId()));
                vo.setFollowed(followService.isFollowed(user.getUserId(), vo.getAuthor().getUserId()));
                vo.setLikeCount(po.getLikeCount());
                if (!user.getId().equals(po.getAuthor().getUserId())) {
                    communityArticleService.modifyCommunityArticleVisit(user, articleId);
                }
            } else {
                communityArticleService.modifyCommunityArticleVisit(null, articleId);
            }
            return ApiResult.ok(vo);
        }
        return ApiResult.error("内容不存在或已删除");
    }

    /**
     * 点赞内容或取消点赞
     *
     * @return
     */
    @PostMapping("/article/like")
    @AccessControl(needLogin = true)
    public ApiResult articleLike(
            @CurrentUser UserPO userPO,
            Long articleId
    ) {
        return ApiResult.ok(communityArticleService.likeToggle(articleId, userPO));
    }


    /**
     * 获取评论列表
     *
     * @param condition
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/comments")
    public ApiResult comments(
            @CurrentUser UserPO userPO,
            CommentsSearchCondition condition,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "20") int size) {
        Page<CommunityCommentPO> pages = communityCommentService.findAll(page, size, condition);
        PageDataVO<CommentsVO> pageDataVO = new PageDataVO<>();
        pageDataVO.setPageCount(pages.getTotalPages());
        pageDataVO.setPageIndex(page);
        pageDataVO.setPageSize(size);
        pageDataVO.setTotal(pages.getTotalElements());
        Map<String, CommunityCommentLikePO> likePOMap = null;
        if (userPO != null) {
            likePOMap = communityCommentService.findByUser(userPO.getUserId(), pages.getContent());
        }

        List<CommentsVO> vos = new ArrayList<>();
        for (CommunityCommentPO p : pages.getContent()) {
            CommentsVO vo = new CommentsVO(p);
            if (userPO != null) {
                //是否点赞
                if (likePOMap.containsKey(p.getId().toString() + '_' + userPO.getId().toString())) {
                    vo.setLiked(true);
                }
            }

            vos.add(vo);
        }

        pageDataVO.setRows(vos);

        return ApiResult.ok(pageDataVO);
    }

    /**
     * 评论
     *
     * @param userPO
     * @param articleId
     * @param content
     * @return
     */
    @PostMapping("/article/comment")
    @AccessControl(needLogin = true)
    public ApiResult comment(
            @CurrentUser UserPO userPO,
            Long articleId,
            String content
    ) {
        CommunityCommentPO po = communityArticleService.comment(articleId, userPO, content);

        return ApiResult.ok(new CommentsVO(po));
    }

    /**
     * 回复评论
     *
     * @return
     */
    @PostMapping("/comment/reply")
    public ApiResult reply(
            Long commentId,
            String content,
            @CurrentUser UserPO userPO
    ) {
        CommunityCommentPO po = communityCommentService.reply(commentId, content, userPO);

        return ApiResult.ok(new CommentsVO(po));
    }

    /**
     * 点赞评论或取消点赞
     *
     * @param user
     * @param commentId
     * @return
     */
    @GetMapping("/comment/like")
    @AccessControl(needLogin = true)
    public ApiResult likeComment(
            @CurrentUser UserPO user,
            Long commentId
    ) {
        return ApiResult.ok(communityCommentService.likeToggle(commentId, user));
    }

    /**
     * 删除文章
     *
     * @param user
     * @param articleId
     * @return
     */
    @GetMapping("/article/delete")
    @AccessControl(needLogin = true)
    public ApiResult deleteArticle(@CurrentUser UserPO user, Long articleId) {
        communityArticleService.delete(user.getUserId(), articleId);
        return ApiResult.ok();
    }
}
